<template>
  <div
    class="home"
    v-if="!appStore.isPhone">
    <el-card>
      <el-row>
        <el-col :span="6">
          <el-statistic
            title="今日物流总数"
            :value="totalLogisticsCountValue" />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="今日物流购买总吨数"
            :value="totalLogisticsBuyTonValue" />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="今日提货总数"
            :value="totalPickCountValue" />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="今日提货应付款总数"
            :value="totalPickPayPriceValue">
          </el-statistic>
        </el-col>
      </el-row>
    </el-card>
    <div style="height: 5px;"></div>
    <el-row>
      <el-col :span="17">
        <el-card>
          <template #header>
            <div class="card_header">
              <span>未填写完成的采购订单列表</span>
            </div>
          </template>
          <Table
            :data="tableOrderData"
            v-loading="tableOrderLoading"
            :height="284">
            <el-table-column
              prop="purchaseOrderName"
              label="采购订单名称"
              min-width="110"
              show-overflow-tooltip
              :resizable="false" />
            <el-table-column
              prop="baseCapitalWarehouseName"
              label="资金仓库简称"
              min-width="110"
              show-overflow-tooltip
              :resizable="false" />
            <el-table-column
              prop="baseRiceBarnSimpleName"
              label="米厂名称"
              min-width="88"
              show-overflow-tooltip
              :resizable="false" />
            <el-table-column
              prop="purchaseOrderNumber"
              label="采购订单编号"
              min-width="110"
              show-overflow-tooltip
              :resizable="false" />
            <el-table-column
              prop="purchaseDate"
              label="采购日期"
              min-width="100"
              show-overflow-tooltip
              :resizable="false">
              <template #default="scope">
                {{ formatDate(scope.row.purchaseDate) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="createUserRealName"
              label="创建人"
              min-width="70"
              show-overflow-tooltip
              :resizable="false" />
            <el-table-column
              label="操作"
              width="100"
              :resizable="false">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="goEdit(scope.row)">
                  去填写
                </el-button>
              </template>
            </el-table-column>
          </Table>
          <el-pagination
            v-model:current-page="paginationOrder.pageNum"
            v-model:page-size="paginationOrder.pageSize"
            :pager-count="5"
            layout="prev, pager, next"
            :total="paginationOrder.total"
            background
            @current-change="handleCurrentOrderChange" />
        </el-card>
        <div style="height: 5px;"></div>
        <el-card>
          <template #header>
            <div class="card_header">
              <span>提货提醒</span>
            </div>
          </template>
          <Table
            :data="tableHomeData"
            v-loading="tableHomeLoading"
            :height="284">
            <el-table-column
              prop="trainNumber"
              show-overflow-tooltip
              label="车次号"
              min-width="70"
              :resizable="false" />
            <el-table-column
              prop="purchaseOrderNumber"
              show-overflow-tooltip
              label="采购订单编号"
              min-width="110"
              :resizable="false" />
            <el-table-column
              prop="purchaseOrderName"
              show-overflow-tooltip
              label="采购订单名称"
              min-width="110"
              :resizable="false" />
            <el-table-column
              prop="residuePredictFinishDays"
              show-overflow-tooltip
              label="剩余预计提货天数"
              min-width="137"
              :resizable="false" />
            <el-table-column
              prop="isArrive"
              show-overflow-tooltip
              label="是否到货"
              min-width="88"
              :resizable="false">
              <template #default="scope">
                {{ scope.row.isArrive ? "是" : "否" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="arriveDate"
              show-overflow-tooltip
              label="到货日期"
              min-width="100"
              :resizable="false">
              <template #default="scope">
                {{ formatDate(scope.row.arriveDate) }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="100"
              :resizable="false">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="goTakeDelivery(scope.row)">
                  去提货
                </el-button>
              </template>
            </el-table-column>
          </Table>
          <el-pagination
            v-model:current-page="paginationHome.pageNum"
            v-model:page-size="paginationHome.pageSize"
            :pager-count="5"
            layout="prev, pager, next"
            :total="paginationHome.total"
            background
            @current-change="handleCurrentHomeChange" />
        </el-card>
      </el-col>
      <el-col :span="7">
        <el-card style="margin-left: 5px;">
          <template #header>
            <div class="card_header">
              <span>通知公告</span>
            </div>
          </template>
          <Table
            :data="tableAnnouncementData"
            v-loading="tableAnnouncementLoading"
            @row-click="rowClick"
            :height="240">
            <el-table-column
              prop="name"
              show-overflow-tooltip
              label="通知名称"
              :resizable="false" />
            <el-table-column
              prop="typeEnumName"
              show-overflow-tooltip
              label="通知类型"
              :resizable="false" />
            <el-table-column
              prop="createUserRealName"
              label="创建人"
              show-overflow-tooltip
              :resizable="false" />
          </Table>
          <el-pagination
            v-model:current-page="paginationAnnouncement.pageNum"
            v-model:page-size="paginationAnnouncement.pageSize"
            :pager-count="4"
            layout="prev, pager, next"
            :total="paginationAnnouncement.total"
            background
            @current-change="handleCurrentAnnouncementChange" />
        </el-card>
        <!-- <el-card style="margin-left: 5px;margin-top: 5px;">
          <template #header>
            <div class="card_header">
              <span>系统磁盘</span>
            </div>
          </template>
          <div
            class="diskEcharts"
            ref="diskSpaceRef"></div>
        </el-card> -->
        <el-card
          v-if="sysEvaluation"
          style="margin-left: 5px;margin-top: 5px;">
          <template #header>
            <div class="card_header">
              <span>系统内存</span>
            </div>
          </template>
          <div class="internal_content">
            <div
              class="internal_echarts"
              ref="internalMemoryRef"></div>
            <div
              class="disk_evaluation"
              v-for="(item, index) in sysEvaluation.diskEvaluationList"
              :key="index">
              <el-tag type="info">
                磁盘：{{ item.diskName }}
              </el-tag>
              <el-tag type="primary">
                总容量：{{ item.totalSpace }}GB
              </el-tag>
              <el-tag type="success">
                剩余容量：{{ item.freeSpace }}GB
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <!-- 手机端页面 -->
  <h5Index v-else></h5Index>
  <!-- 查看 -->
  <View
    ref="viewRef"
    :rowData="rowData" />
</template>

<script setup>
import ApiSysInfo from "@/api/modules/sys-info"
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import ApiPurchaseOrder from "@/api/modules/purchase-order"
import ApiHome from "@/api/modules/home"
import { formatDate } from "@/common/utils/date";
import { useRouter } from "vue-router"
// import config from "@/common/element-plus/config";
import Table from "@/components/Table.vue"
import View from "@/views/system-information/component/View.vue"
import h5Index from "./h5Index.vue";
import { useAppStore } from "@/stores/app"
import { useTransition } from "@vueuse/core"

/** 路由 */
const router = useRouter()
/** 查看组件实例 */
const viewRef = ref()
const rowData = ref({})
/** 磁盘空间饼图 */
// const diskSpaceRef = ref()
/** 内存饼图 */
const internalMemoryRef = ref()
/** 系统信息 */
const sysEvaluation = ref()
// 枚举类型列表
const enumList = ref([])
// 采购订单分页
const tableOrderData = ref([])
const tableOrderLoading = ref(false)
const paginationOrder = ref({
  pageNum: 1,
  pageSize: 5,
  total: 0
})
// 提货分页
const tableHomeData = ref([])
const tableHomeLoading = ref(false)
const paginationHome = ref({
  pageNum: 1,
  pageSize: 5,
  total: 0
})
// 公告分页
const tableAnnouncementData = ref([])
const tableAnnouncementLoading = ref(false)
const paginationAnnouncement = ref({
  pageNum: 1,
  pageSize: 5,
  total: 0
})
// 今日统计信息
const statisticsInfo = ref({})
const totalLogisticsCount = ref(0)
const totalLogisticsBuyTon = ref(0)
const totalPickCount = ref(0)
const totalPickPayPrice = ref(0)

/** 采购订单列表分页查询 */
const purchaseOrderSelectPage = async () => {
  tableOrderLoading.value = true
  const data = await ApiPurchaseOrder.selectPage({}, {
    pageNum: paginationOrder.value.pageNum,
    pageSize: paginationOrder.value.pageSize
  })
  tableOrderData.value = data.data.records
  paginationOrder.value.total = data.data.total
  tableOrderLoading.value = false
}
const handleCurrentOrderChange = async (val) => {
  paginationOrder.value.pageNum = val
  await purchaseOrderSelectPage()
}

/** 提货列表分页查询 */
const trainPickPredictEndDateRemind = async () => {
  tableHomeLoading.value = true
  const data = await ApiHome.trainPickPredictEndDateRemind({
    pageNum: paginationHome.value.pageNum,
    pageSize: paginationHome.value.pageSize
  })
  tableHomeData.value = data.data.records
  paginationHome.value.total = data.data.total
  tableHomeLoading.value = false
}
const handleCurrentHomeChange = async (val) => {
  paginationHome.value.pageNum = val
  await trainPickPredictEndDateRemind()
}

/** 公告列表分页查询 */
const selectPage = async () => {
  tableAnnouncementLoading.value = true
  const data = await ApiSysInfo.selectPage({}, {
    pageNum: paginationAnnouncement.value.pageNum,
    pageSize: paginationAnnouncement.value.pageSize
  })
  tableAnnouncementData.value = data.data.records
  tableAnnouncementData.value.forEach(item => {
    const find = enumList.value.find(val => val.key === item.typeEnum)
      if (find) item.typeEnumName = find.value
  })
  paginationAnnouncement.value.total = data.data.total
  tableAnnouncementLoading.value = false
}
const handleCurrentAnnouncementChange = async (val) => {
  paginationAnnouncement.value.pageNum = val
  await selectPage()
}

/** 获取今日统计信息 */
const todayStatistics = async () => {
  const data = await ApiHome.todayStatistics()
  statisticsInfo.value = data.data
  totalLogisticsCount.value = statisticsInfo.value.totalLogisticsCount
  totalLogisticsBuyTon.value = statisticsInfo.value.totalLogisticsBuyTon
  totalPickCount.value = statisticsInfo.value.totalPickCount
  totalPickPayPrice.value = statisticsInfo.value.totalPickPayPrice
}

// 实现数值的变化动效
const totalLogisticsCountValue = useTransition(totalLogisticsCount, {
  duration: 1500,
})
const totalLogisticsBuyTonValue = useTransition(totalLogisticsBuyTon, {
  duration: 1500,
})
const totalPickCountValue = useTransition(totalPickCount, {
  duration: 1500,
})
const totalPickPayPriceValue = useTransition(totalPickPayPrice, {
  duration: 1500,
})

/** 获取枚举类型 */
const getSysInfoTypeEnum = async () => {
  const data = await ApiSysInfo.getSysInfoTypeEnum()
  enumList.value = data.data
};

/** 获取系统信息 */
const getSysPerformanceEvaluation = async () => {
  const data = await ApiSysInfo.getSysPerformanceEvaluation()
  sysEvaluation.value = data.data
}

/** 跳转采购订单修改页面 */
const goEdit = (row) => {
  router.push({
    path: "/purchase-order-insert/index",
    query: { purchaseOrderNumber: row.purchaseOrderNumber }
  })
}

/** 跳转车次列表页面 */
const goTakeDelivery = (row) => {
  router.push({
    path: "/train-inventory/index",
    query: { trainNumber: row.trainNumber }
  })
}

/** 查看通知 */
const rowClick = (row) => {
  viewRef.value.visibility = true
  rowData.value = row.row
}

const appStore = useAppStore()

onMounted(async () => {
  if (appStore.isPhone) return
  await getSysInfoTypeEnum()
  await purchaseOrderSelectPage()
  await trainPickPredictEndDateRemind()
  await selectPage()
  await todayStatistics()
  await getSysPerformanceEvaluation()
  // 基于准备好的dom，初始化echarts实例
  // const diskSpaceChart = echarts.init(diskSpaceRef.value);
  const internalMemoryChart = echarts.init(internalMemoryRef.value);
  // 绘制图表
  // diskSpaceChart.setOption({
  //   tooltip: {
  //     trigger: "item"
  //   },
  //   legend: {
  //     left: "left",
  //     top: "top"
  //   },
  //   series: [
  //     {
  //       name: "磁盘空间使用情况",
  //       type: "pie",
  //       radius: "50%",
  //       data: [
  //         { value: sysEvaluation.value.diskEvaluationList[0].totalSpace, name: "磁盘总容量" },
  //         { value: sysEvaluation.value.diskEvaluationList[0].freeSpace, name: "磁盘剩余容量" },
  //       ],
  //       emphasis: {
  //         itemStyle: {
  //           shadowBlur: 10,
  //           shadowOffsetX: 0,
  //           shadowColor: "rgba(0, 0, 0, 0.5)"
  //         }
  //       },
  //       label: {
  //         show: false,
  //         position: "center"
  //       },
  //     }
  //   ]
  // });
  internalMemoryChart.setOption({
    tooltip: {
      trigger: "item"
    },
    legend: {
      // orient: "vertical",
      left: "left",
      top: "top"
    },
    series: [
      {
        name: "jvm-内存",
        type: "pie",
        radius: "50%",
        data: [
          { value: sysEvaluation.value.maxMemory, name: "最大可用内存" },
          { value: sysEvaluation.value.totalMemory, name: "当前初始化总内存" },
          { value: sysEvaluation.value.usedMemory, name: "目前已用内存" },
          { value: sysEvaluation.value.freeMemory, name: "空闲内存" },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        },
        label: {
          show: false,
          position: "center"
        }
      }
    ]
  });
  // 如果容器尺寸变化 调用 resize
  window.addEventListener("resize", () => {
    // diskSpaceChart.resize();
    internalMemoryChart.resize();
  });
})
</script>

<style lang="scss" scoped>
.home {
  height: calc(100vh - 90px);
  overflow-y: auto;

  .el-row {
    align-items: flex-start;
  }

  :deep(.el-card__header) {
    padding: 10px 20px;

    span {
      font-family: sans-serif;
      font-size: 13px;
    }
  }

  :deep(.el-card__body) {
    padding: 10px;
  }

  :deep(.el-statistic__content) {
    text-align: center;
  }

  :deep(.el-statistic__head) {
    text-align: center;
  }

  .el-pagination {
    padding: 10px;
    padding-bottom: 0;
    justify-content: end;
  }

  // .diskEcharts {
  //   height: 280px;
  // }

  .disk_evaluation {
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-top: 6px;
  }

  .internal_content {
    height: 370px;
  }

  .internal_echarts {
    height: 270px;
  }
}
</style>
